<template>
	<view class="contnt">
		<view class="flex align-center flex-column">
			<view class="logo">
				<image src="/static/logo.png" mode="aspectFit" class="image"></image>
			</view>
			<view class="btn">
				<u-button icon="weixin-fill" iconColor="#ffffff" shape="circle" @click="wxMiniLogin()"
					:loading="loginLoading" color="linear-gradient(-90deg,#1cc48c, #96E8BA)" text="微信一键登录">
				</u-button>
			</view>
			<view class="text-center mt-2">
				<text class="text-light-black">登录表示同意</text>
				<text class="text-success ml-1">用户使用协议/隐私政策</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loginLoading: false,
				code: "",
				inviter: uni.getStorageSync('inviter'),
			}
		},
		onShow() {
			//页面显示先调用wx.login获取code session未过期使用此code
			uni.login({
				provider: "weixin",
				success: (res) => {
					this.code = res.code;
				},
			});
		},
		methods: {
			wxMiniLogin() {
				var _this = this;
				uni.getUserProfile({
					desc: "获取你的昵称、头像、地区及性别",
					success({
						iv,
						encryptedData,
						signature,
						rawData
					}) {
						uni.checkSession({
							success: (res) => {
								const postData = {
									iv,
									encryptedData,
									signature,
									rawData,
									code: _this.code
								}
								_this.requestLogin(postData)
							},
							fail: () => {
								uni.login({
									provider: "weixin",
									success: (res) => {
										let code = res.code;
										const postData = {
											iv,
											encryptedData,
											signature,
											rawData,
											code
										}
										_this.requestLogin(postData)
									},
								});
							},
						});
					}
				})
			},
			requestLogin(postData) {
				let {
					iv,
					encryptedData,
					signature,
					rawData,
					code
				} = postData
				postData.plat_type = this.$platType;
				postData.inviter = this.inviter;
				this.loginLoading = true;
				this.$http.requestApi('POST', 'client/wxMiniLogin', postData).then(res => {
					const resData = res.data;
					const resCode = res.status;
					this.loginLoading = false
					if (resCode == 200) {
						this.$store.commit('login', resData)
						//获取上一级页面地址
						let pages = getCurrentPages(); //页面对象
						let prevpage = pages[pages.length - 2]; //上一个页面对象
						let fullPath = prevpage.$page.fullPath;
						if (fullPath) {
							uni.reLaunch({
								url: fullPath,
							})
						} else {
							uni.navigateBack({
								delta: 1
							})
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.contnt {
		width: 90%;
		margin: 0 auto;
	}

	.logo {
		width: 100%;
		text-align: center;
		margin: 120rpx 0;

		.image {
			width: 200upx;
			height: 200upx;
			padding: 1rpx;
		}
	}

	.btn {
		width: 100%;
	}

	.text-center {
		font-size: 28rpx;
	}
</style>